<?php

use app\service\auth;
use app\service\member as memberService;
use Illuminate\Database\Capsule\Manager as DB;


class Agent_AgentController extends CommonController
{
    public function customerAction()
    {
        $params = $this->get();
        if (!is_integer(intval($params['mobile']))) {
            throw new Exception('请输入用户ID或手机号码');
        }
        if (strlen($params['mobile']) == 11) {
            if (!preg_match("/^1[3456789][0-9]{9}$/", $params['mobile'])) {
                throw new Exception('手机号码格式有误');
            } else {
                $user = memberModel::firstWhere('phone', $params['mobile']);
            }
        } else {
            $user = memberModel::find($params['mobile']);
        }
        if (!$user) {
            throw new Exception('未查找到匹配用户');
        }
        json(['code' => 1, 'msg' => '获取成功', 'data' => auth::userinfo($user)]);
    }

    public function teamCountAction()
    {
        if ($this->get('uid')) {
            $member = memberModel::find($this->get('uid'));
        } else {
            $member = auth::getUser();
        }
        $data = memberchildrenModel::teamcount($member);
        json(['code' => 1, 'msg' => '团队人数', 'data' => $data]);
    }

    public function referrerAction()
    {
        $member = auth::getUser();
        $inviter = memberModel::find($member->parent_member_id);
        json(['code' => 1, 'msg' => '用户数据', 'data' => $inviter ? auth::userinfo($inviter) : null]);
    }

    public function searchNextAction()
    {
        $user = auth::getUser();
        $type = $this->get('type', 'direct');
        $pid = $this->get('pid', $user->id);
        $search = $this->get('search') ?: '';
        if (empty($type)) {
            throw new Exception('参数错误');
        }
        $page = $this->get('page', 1);
        $size = $this->get('size', 20);
        $offset = ($page - 1) * $size;
        $model = memberchildrenModel::where(function ($query) use ($type) {
            if ($type == 'direct') {
                $query->where('level', 1);
            }
            if ($type == 'other') {
                $query->where('level', '>', 1);
            }
        })->where('member_id', $pid);
        if (!empty($search)) {
            $model = $model->whereHas('child', function ($query) use ($search) {
                $query
                    ->where('id', 'like', "%{$search}%")
                    ->orWhere('nickname', 'like', "%{$search}%")
                    ->orWhere('phone', 'like', "%{$search}%");
            });
        }
        $list = $model->orderBy('id', 'desc')->offset($offset)->limit($size)->get();

        $userList = [];
        foreach ($list as $mc) {
            $item = [
                'id' => $mc->child->id,
                'nickname' => $mc->child->nickname,
                'mobile' => $mc->child->phone,
                'avatar'    =>$mc->child->avatar,
                'level'     =>$mc->child->level_info ? $mc->child->level_info->name : '--',
                'createtime' => strtotime($mc->child->created_at),
            ];
            $item['team'] = memberchildrenModel::teamchildcount($mc->child->id);
            array_push($userList, $item);
        }

        json(['code' => 1, 'msg' => '队员列表', 'data' => $userList]);
    }

    public function teamlistAction()
    {
        $user = auth::getUser();
        $type = $this->get('type', '');
        $pid = $this->get('pid', $user->id);
        if (empty($type)) {
            throw new Exception('参数错误');
        }
        $page = $this->get('page', 1);
        $size = $this->get('size', 10);
        $offset = ($page - 1) * $size;
        $model = memberchildrenModel::where(function ($query) use ($type) {
            if ($type == 'direct') {
                $query->where('level', 1);
            }
            if ($type == 'other') {
                $query->where('level', '>', 1);
            }
        })
            ->where('member_id', $pid)
            ->where('children_deleted', 0);
        $total = $model->count();
        $list = $model->orderBy('id', 'desc')->offset($offset)->limit($size)->get();

        $userList = [];
        foreach ($list as $mc) {
//            dump($mc->child->level_info);
            $item = [
                'id' => $mc->child->id,
                'nickname' => $mc->child->nickname,
                'mobile' => $mc->child->phone,
                'avatar'    =>$mc->child->avatar,
                'level'     =>$mc->child->level_info ? $mc->child->level_info->name : '--',
                'image'     => $mc->child->level_info? $mc->child->level_info->image:'',
                'createtime' => strtotime($mc->child->created_at),
            ];
            $item['team'] = memberchildrenModel::teamchildcount($mc->child->id);
            array_push($userList, $item);
        }

        json(['code' => 1, 'msg' => '队员列表', 'data' => ['total' => $total, 'list'  => $userList]]);
    }

    public function kpiAction()
    {
        if ($this->get('uid')) {
            $member = memberModel::find($this->get('uid'));
        } else {
            $member = auth::getUser();
        }
        $query = (new \orderModel)
            ->with('member')
            ->where('status', '>', 0)
            ->where(function ($query) use ($member) {
                $id = $member->id;
                $query->whereRaw("customer_id in (SELECT children_id from cs_member_children where `member_id`={$id})")
                    ->orWhere(function ($query) use ($id) {
                        $query->where('customer_id', 0)
                            ->whereRaw("member_id in (SELECT children_id from cs_member_children where `member_id`={$id})");
                    })->orWhere('customer_id', $id)
                    ->orWhere(function ($query) use ($id) {
                        $query->where('customer_id', 0)
                            ->where('member_id', $id);
                    });
            })->whereNotExists(function ($query) {
                $query->from('order_item')->whereColumn('order_item.order_id', 'order.id')
                    ->where('refund_status', '>', 0);
            });
        $all_num = $query->count();
        $all_amount = memberModel::where('id', $member->id)->value('team_consume');

        $query = (new \orderModel)
            ->with('member')
            ->where('status', '>', 0)
            ->where(function ($query) use ($member) {
                $id = $member->id;
                $query->whereRaw("customer_id in (SELECT children_id from cs_member_children where `level`=1 and `member_id`={$id})")
                    ->orWhere(function ($query) use ($id) {
                        $query->where('customer_id', 0)
                            ->whereRaw("member_id in (SELECT children_id from cs_member_children where `level`=1 and `member_id`={$id})");
                    });
            })->whereNotExists(function ($query) {
                $query->from('order_item')->whereColumn('order_item.order_id', 'order.id')
                    ->where('refund_status', '>', 0);
            });
        $direct_num = $query->count();
        $direct_amount = $query->sum('pay_fee');

        $data = [
            "all_num"       => (int) $all_num,
            "all_amount"    => bcadd($all_amount, '0', 2),
            "direct_num"    => (int) $direct_num,
            "direct_amount" => bcadd($direct_amount, '0', 2),
        ];
        json(['code' => 1, 'msg' => '', 'data' => $data]);
    }

    public function kpilistAction()
    {
        $mode = $this->get('mode', 'all');
        $type = $this->get('type', 'yes');
        $page = $this->get('page', 1);

        $date = $this->get('date', '今日');
        if ($date == '今日') {
            $start_on = date('Y-m-d');
            $end_on = date('Y-m-d 23:59:59');
        } else {
            $date_range = explode('-', $date);
            $start_on = date('Y-m-d', strtotime(str_replace('.', '/', $date_range[0])));
            $end_on = date('Y-m-d 23:59:59', strtotime(str_replace('.', '/', $date_range[1])));
        }

        $member = auth::getUser();
        $params = [
            'id'           => $member->id,
            'start_on'     => $start_on,
            'end_on'       => $end_on,
            'keywordsType' => '',
            'keywords'     => '',
            'page'         => $page,
        ];

        if ($mode == 'all') {
            if ($type == 'yes') {
                $result = memberService::teamConsume($params);
            } else {
                $result = memberService::teamConsumeRefund($params);
            }
        } else {
            if ($type == 'yes') {
                $result = memberService::teamConsumeV1($params);
            } else {
                $result = memberService::teamConsumeV1Refund($params);
            }
        }

        $data = [
            'amount' => $result['amount'] ?? 0,
            'total'  => $result['total'] ?? 0,
            'list'   => $result['rows'] ?? [],
        ];

        json(['code' => 1, 'msg' => '团队业绩', 'data' => $data ?? null]);
    }

    public function mykpilistAction()
    {
        $mode = $this->get('mode', 'all');
        $type = $this->get('type', 'yes');
        $page = $this->get('page', 1);

        $date = $this->get('date', '今日');
        if ($date == '今日') {
            $start_on = date('Y-m-d');
            $end_on = date('Y-m-d 23:59:59');
        } else {
            $date_range = explode('-', $date);
            $start_on = date('Y-m-d', strtotime(str_replace('.', '/', $date_range[0])));
            $end_on = date('Y-m-d 23:59:59', strtotime(str_replace('.', '/', $date_range[1])));
        }

        $member = auth::getUser();
        $params = [
            'id'           => $member->id,
            'start_on'     => $start_on,
            'end_on'       => $end_on,
            'keywordsType' => '',
            'keywords'     => '',
            'page'         => $page,
            'only_me'      => 1,
        ];

        if ($mode == 'all') {
            if ($type == 'yes') {
                $result = memberService::totalConsume($params);
            } else {
                $result = memberService::totalConsumeRefund($params);
            }
        } else {
            if ($type == 'yes') {
                $result = memberService::teamConsumeV1($params);
            } else {
                $result = memberService::teamConsumeV1Refund($params);
            }
        }

        $data = [
            'amount' => $result['amount'] ?? 0,
            'total'  => $result['total'] ?? 0,
            'list'   => $result['rows'] ?? [],
        ];

        json(['code' => 1, 'msg' => '团队业绩', 'data' => $data ?? null]);
    }

    public function rankingAction()
    {
        $modes = ['today', 'thisweek', 'thismonth', 'yesterday', 'lastweek', 'lastmonth'];
        foreach ($modes as $mode) {
            $result[$mode] = DB::table('ranking_list')
                ->where('mode', $mode)
                ->orderBy('consume', 'desc')
                ->limit(10)
                ->get();
        }
        json(['code' => 1, 'msg' => '业绩排行耪', 'data' => $result]);
    }
}
